<template>
	<div class="blog-comment-container">
		<message-area
			title="评论列表"
			:subTitle="`${data.total}`"
			:list="data.rows"
			:isListLoading="isDataLoading"
			@submit="handleSubmit"
			id="comment-container"
		></message-area>
		<div class="more" :class="{ moreClass: hasMore }">{{ slideText }}</div>
	</div>
</template>

<script>
// 读取评论列表，加载数据给子组件传递
import MessageArea from '@/components/MessageArea'
import fetchData from '@/mixins/fetchData'
import { getComment, submitComment } from '@/api/blog'
export default {
	name: 'BlogComment',
	mixins: [fetchData({ total: 0, rows: [] })],
	components: { MessageArea },
	data() {
		return {
			page: 1,
			limit: 10,
		}
	},
	created() {
		// 监听滑动
		this.$bus.$on('mainScroll', this.handleScroll)
	},
	computed: {
		hasMore() {
			return this.data.rows.length < this.data.total
		},
		// 显示“下滑加载更多字样”
		slideText() {
			return this.hasMore ? '----下滑加载更多----' : '----没有更多了----'
		},
	},
	methods: {
		handleScroll(domEle) {
			if (this.isDataLoading || !domEle) return
			const scrollTop = domEle.scrollTop
			const bottomHeight = domEle.scrollHeight - domEle.clientHeight
			if (bottomHeight - scrollTop < 20) {
				this.fetchMore()
			}
		},
		async fetchData() {
			return await getComment(this.$route.params.id, this.page, this.limit)
		},
		async fetchMore() {
			if (!this.hasMore) return
			this.isDataLoading = true
			this.page++
			const res = await this.fetchData()
			this.data.total = res.total
			this.data.rows = this.data.rows.concat(res.rows)
			this.isDataLoading = false
		},
		async handleSubmit(data, callback) {
			const res = await submitComment({
				blog: this.$route.params.id,
				...data,
			})
			this.data.rows.unshift(res)
			this.data.total++
			callback('评论成功')
		},
	},
	beforeDestroy() {
		this.$bus.$off('mainScroll', this.handleScroll)
	},
}
</script>

<style lang="less" scoped>
@import '~@/styles/basic/var.less';
.more {
	text-align: center;
	color: @gray;
}
.moreClass {
	color: @primary;
}
</style>
